<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { Edit, Message, Lock, Setting, Calendar, Bell, FirstAidKit, User, Trophy, Notebook } from '@element-plus/icons-vue'
import { useDoctorStore } from '@/stores/doctor'
import { getDoctorProfile, updateDoctorProfile, uploadAvatar } from '@/apis/doctor/doctorProfileAPI'
import { ElMessage } from 'element-plus'
import type { DoctorProfile } from '@/types/doctor'
import MessageCenter from '@/views/doctorViews/message/index.vue'

// 获取医生store
const doctorStore = useDoctorStore()

// 加载状态
const loading = ref(false)

// 医生信息
const doctorInfo = ref({
  name: '',
  avatar: '',
  gender: '',
  age: 0,
  title: '',
  department: '',
  hospital: '',
  phone: '',
  email: '',
  address: '',
  specialty: '',
  introduction: '',
  education: '',
  certifications: [],
  workYears: 0,
  registrationDate: '',
  birthday: ''
})

// 获取医生信息
const fetchDoctorProfile = async () => {
  loading.value = true
  try {
    const res = await getDoctorProfile()
    if (res.status === 200 && res.data) {
      // 更新store中的医生信息
      doctorStore.setDoctorProfileFromAPI(res.data)

      // 更新本地医生信息
      doctorInfo.value.name = res.data.name || ''
      doctorInfo.value.phone = res.data.phone || ''
      doctorInfo.value.department = res.data.department || ''
      doctorInfo.value.email = res.data.email || ''
      doctorInfo.value.avatar = res.data.avatar || ''
      doctorInfo.value.gender = res.data.sex === '0' ? '男' : '女'
      doctorInfo.value.birthday = res.data.birthday || ''
      doctorInfo.value.title = res.data.title || ''
      doctorInfo.value.specialty = res.data.goodAt || ''
      doctorInfo.value.introduction = res.data.introduction || ''
      doctorInfo.value.hospital = res.data.hospital || ''
      doctorInfo.value.address = res.data.address || ''
      doctorInfo.value.education = res.data.education || ''
      doctorInfo.value.certifications = res.data.certifications || []
      doctorInfo.value.workYears = res.data.workYears || 0
      doctorInfo.value.registrationDate = res.data.registrationDate || ''

      // 如果有生日信息，计算年龄
      if (res.data.birthday) {
        const birthDate = new Date(res.data.birthday)
        const today = new Date()
        let age = today.getFullYear() - birthDate.getFullYear()
        const monthDiff = today.getMonth() - birthDate.getMonth()
        if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
          age--
        }
        doctorInfo.value.age = age
      } else {
        doctorInfo.value.age = 0
      }
    } else {
      ElMessage.error('获取医生信息失败')
    }
  } catch (error) {
    console.error('获取医生信息出错:', error)
    ElMessage.error('获取医生信息出错')
  } finally {
    loading.value = false
  }
}

// 当前激活的标签页
const activeTab = ref('basic')

// 是否显示编辑表单
const showEditForm = ref(false)

// 切换编辑表单显示状态
const toggleEditForm = () => {
  showEditForm.value = !showEditForm.value
}

// 处理头像上传
const handleAvatarChange = async (file: any) => {
  if (!file) return

  try {
    loading.value = true
    // 直接使用FormData上传文件
    const avatarData = {
      file: file.raw
    }

    const res = await uploadAvatar(avatarData)
    if (res.status === 200) {
      ElMessage.success('头像上传成功')
      // 创建临时URL用于本地显示
      const tempUrl = URL.createObjectURL(file.raw)
      // 更新本地头像显示
      doctorInfo.value.avatar = tempUrl
      // 重新获取医生信息
      await fetchDoctorProfile()
    } else {
      ElMessage.error('头像上传失败，请稍后重试')
    }
  } catch (error) {
    console.error('上传头像失败:', error)
    ElMessage.error('上传头像失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 保存医生信息
const saveDoctorInfo = async () => {
  loading.value = true
  try {
    // 构建更新请求数据
    const updateData: any = {
      id: Number(doctorStore.doctorId), // 将doctorId转换为数字类型
      name: doctorInfo.value.name,
      title: doctorInfo.value.title,
      department: doctorInfo.value.department,
      hospital: doctorInfo.value.hospital,
      phone: doctorInfo.value.phone,
      email: doctorInfo.value.email,
      sex: doctorInfo.value.gender === '男' ? '0' : '1',
      introduction: doctorInfo.value.introduction,
      goodAt: doctorInfo.value.specialty,
      address: doctorInfo.value.address
    }

    // 如果有生日信息，添加到请求数据中
    if (doctorInfo.value.birthday) {
      updateData.birthday = doctorInfo.value.birthday
    }

    const res = await updateDoctorProfile(updateData)
    if (res.status === 200) {
      ElMessage.success('保存成功')
      showEditForm.value = false
      // 重新获取最新的医生信息
      fetchDoctorProfile()
    } else {
      ElMessage.error(res.message || '保存失败')
    }
  } catch (error) {
    console.error('保存医生信息出错:', error)
    ElMessage.error('保存医生信息出错')
  } finally {
    loading.value = false
  }
}

// 统计数据 - 实际项目中可能需要从API获取
const statistics = ref({
  patients: 1256,
  appointments: 328,
  consultations: 156,
  rating: 4.9
})

// 组件挂载时获取医生信息
onMounted(() => {
  fetchDoctorProfile()
})
</script>

<template>
  <div class="profile-container">
    <el-loading v-model:full-screen="loading" background="rgba(255, 255, 255, 0.7)" />
    <el-row :gutter="20">
      <!-- 左侧医生信息卡片 -->
      <el-col :span="8">
        <el-card shadow="hover" class="doctor-card">
          <div class="doctor-header">
            <div class="avatar-container">
              <el-avatar :size="80" :src="doctorInfo.avatar">{{ doctorInfo.name.charAt(0) }}</el-avatar>
              <div class="avatar-upload">
                <el-upload
                  class="avatar-uploader"
                  action="#"
                  :auto-upload="false"
                  :show-file-list="false"
                  :on-change="handleAvatarChange">
                  <el-icon class="avatar-uploader-icon"><Edit /></el-icon>
                </el-upload>
              </div>
            </div>
            <h2 class="doctor-name">{{ doctorInfo.name }}</h2>
            <p class="doctor-title">{{ doctorInfo.title }} | {{ doctorInfo.department }}</p>
            <p class="doctor-hospital">{{ doctorInfo.hospital }}</p>
            <el-button type="primary" size="small" @click="toggleEditForm">
              <el-icon><Edit /></el-icon>
              编辑资料
            </el-button>
          </div>

          <el-divider />

          <div class="doctor-stats">
            <div class="stat-item">
              <div class="stat-value">{{ statistics.patients }}</div>
              <div class="stat-label">患者数</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ statistics.appointments }}</div>
              <div class="stat-label">预约数</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ statistics.rating }}</div>
              <div class="stat-label">评分</div>
            </div>
          </div>

          <el-divider />

          <div class="contact-info">
            <div class="info-item">
              <el-icon><Message /></el-icon>
              <span>{{ doctorInfo.email }}</span>
            </div>
            <div class="info-item">
              <el-icon><User /></el-icon>
              <span>{{ doctorInfo.workYears }}年工作经验</span>
            </div>
            <div class="info-item">
              <el-icon><Setting /></el-icon>
              <span>注册时间: {{ doctorInfo.registrationDate }}</span>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧内容区域 -->
      <el-col :span="16">
        <!-- 编辑表单 -->
        <el-card v-if="showEditForm" shadow="hover" class="mb-4">
          <template #header>
            <div class="card-header">
              <span>编辑个人信息</span>
            </div>
          </template>

          <el-form label-position="right" label-width="100px">
            <el-form-item label="姓名">
              <el-input v-model="doctorInfo.name" />
            </el-form-item>
            <el-form-item label="性别">
              <el-radio-group v-model="doctorInfo.gender">
                <el-radio label="男">男</el-radio>
                <el-radio label="女">女</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="生日">
              <el-date-picker
                v-model="doctorInfo.birthday"
                type="date"
                placeholder="选择生日"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
            <el-form-item label="职称">
              <el-select v-model="doctorInfo.title">
                <el-option label="主任医师" value="主任医师" />
                <el-option label="副主任医师" value="副主任医师" />
                <el-option label="主治医师" value="主治医师" />
                <el-option label="住院医师" value="住院医师" />
              </el-select>
            </el-form-item>
            <el-form-item label="科室">
              <el-input v-model="doctorInfo.department" />
            </el-form-item>
            <el-form-item label="医院">
              <el-input v-model="doctorInfo.hospital" />
            </el-form-item>
            <el-form-item label="手机号码">
              <el-input v-model="doctorInfo.phone" />
            </el-form-item>
            <el-form-item label="邮箱">
              <el-input v-model="doctorInfo.email" />
            </el-form-item>
            <el-form-item label="地址">
              <el-input v-model="doctorInfo.address" />
            </el-form-item>
            <el-form-item label="专长">
              <el-input v-model="doctorInfo.specialty" type="textarea" />
            </el-form-item>
            <el-form-item label="个人简介">
              <el-input v-model="doctorInfo.introduction" type="textarea" :rows="3" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveDoctorInfo">保存</el-button>
              <el-button @click="toggleEditForm">取消</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 医生详细信息标签页 -->
        <el-card v-else shadow="hover" class="mb-4">
          <template #header>
            <div class="card-header">
              <span>个人信息</span>
            </div>
          </template>

          <el-tabs v-model="activeTab" class="demo-tabs">
            <el-tab-pane label="基本信息" name="basic">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="姓名">{{ doctorInfo.name }}</el-descriptions-item>
                <el-descriptions-item label="性别">{{ doctorInfo.gender }}</el-descriptions-item>
                <el-descriptions-item label="年龄">{{ doctorInfo.age }}</el-descriptions-item>
                <el-descriptions-item label="职称">{{ doctorInfo.title }}</el-descriptions-item>
                <el-descriptions-item label="科室">{{ doctorInfo.department }}</el-descriptions-item>
                <el-descriptions-item label="医院">{{ doctorInfo.hospital }}</el-descriptions-item>
                <el-descriptions-item label="手机号码">{{ doctorInfo.phone }}</el-descriptions-item>
                <el-descriptions-item label="邮箱">{{ doctorInfo.email }}</el-descriptions-item>
                <el-descriptions-item label="地址" :span="2">{{ doctorInfo.address }}</el-descriptions-item>
              </el-descriptions>
            </el-tab-pane>

            <el-tab-pane label="专业信息" name="professional">
              <el-descriptions :column="1" border>
                <el-descriptions-item label="专长">{{ doctorInfo.specialty }}</el-descriptions-item>
                <el-descriptions-item label="个人简介">{{ doctorInfo.introduction }}</el-descriptions-item>
                <el-descriptions-item label="教育背景">{{ doctorInfo.education }}</el-descriptions-item>
                <el-descriptions-item label="资质认证">
                  <el-tag v-for="(cert, index) in doctorInfo.certifications" :key="index" class="cert-tag">
                    {{ cert }}
                  </el-tag>
                </el-descriptions-item>
              </el-descriptions>
            </el-tab-pane>

            <el-tab-pane label="账户安全" name="security">
              <el-empty description="暂无安全设置" />
            </el-tab-pane>
          </el-tabs>
        </el-card>

        <!-- 消息中心区域 -->
        <el-card shadow="hover" class="message-container">
          <template #header>
            <div class="card-header">
              <span>我的消息</span>
            </div>
          </template>

          <div class="message-center-wrapper">
            <MessageCenter />
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped>
.profile-container {
  padding: 20px;
}

.doctor-card {
  height: 100%;
}

.doctor-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-bottom: 20px;
}

.avatar-container {
  position: relative;
  margin-bottom: 10px;
}

.avatar-upload {
  position: absolute;
  bottom: 0;
  right: 0;
}

.avatar-uploader .avatar-uploader-icon {
  font-size: 16px;
  color: #fff;
  width: 24px;
  height: 24px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 50%;
  background-color: #409EFF;
  cursor: pointer;
}

.doctor-name {
  margin: 16px 0 8px;
  font-size: 22px;
  font-weight: bold;
}

.doctor-title {
  margin: 0 0 8px;
  color: #666;
  font-size: 14px;
}

.doctor-hospital {
  margin: 0 0 16px;
  color: #666;
  font-size: 14px;
}

.doctor-stats {
  display: flex;
  justify-content: space-around;
  padding: 20px 0;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}

.stat-label {
  font-size: 12px;
  color: #666;
  margin-top: 8px;
}

.contact-info {
  padding: 20px 0;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.info-item .el-icon {
  margin-right: 8px;
  color: #409EFF;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.mb-4 {
  margin-bottom: 16px;
}

.message-container {
  margin-bottom: 20px;
}

.message-center-wrapper {
  /* 移除消息中心组件内部的padding，避免嵌套卡片的双重内边距 */
  margin: -20px;
}

.message-center-wrapper :deep(.message-page-container) {
  padding: 0;
}

.message-center-wrapper :deep(.message-card) {
  box-shadow: none;
  border: none;
}

.message-center-wrapper :deep(.el-card__header) {
  display: none; /* 隐藏内部卡片的标题，因为我们已经有了外部卡片的标题 */
}

/* 消息中心其他样式会从组件内部继承 */

.cert-tag {
  margin-right: 8px;
  margin-bottom: 8px;
}
</style>
